<!--
 * @Description: 报告列表
 * @Author: qingyang
 * @Date: 2023-09-20 16:04:17
 * @LastEditors: qingyang
 * @LastEditTime: 2023-09-20 10:17:44
-->
<template>
  <div class="report-list">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerRightButton>
        <el-button @click="handleAdd" type="primary" v-btnPermission="'PCF_LCA_REPORT_CREATE'">
          <CIcon type="c-xian-xinjian" class="g-mr4"></CIcon>新建报告
        </el-button>
      </template>
      <template #modelInfo="{ scope }">
        <CTableColumn
          :main-text="scope.row.modelName"
          :sub-text="`编码：${empty(scope.row.modelCode)}`"
          sub-text-color="#435970"
        >
        </CTableColumn>
      </template>
      <template #standard="{ scope }">
        {{ StandardDetailMap[scope.row.standard] }}
      </template>
      <template #unitResult="{ scope }">
        {{
          scope.row.unitResult
            ? `${renderResultUnit(scope.row.unitResult)}/${scope.row.referenceFlowUnit ?? ''}`
            : '-'
        }}
      </template>

      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
    </CPageTable>
    <ModelSelectDialog
      v-model:visible="dialogVisible"
      @select="handleSelect"
      title="选择模型创建报告"
    ></ModelSelectDialog>
    <ReportChartView :reportNo="reportNo" @finish="finishHandle"> </ReportChartView>
  </div>
</template>
<script lang="ts">
export default {
  name: 'ReportList'
};
</script>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useReportList } from './useReportList';
import { empty } from '@/utils/index';
import { useMessage } from '@/hooks/useMessage';
import { useExport } from '@/hooks/useExport';
import ReportChartView from '@/businessComponents/ReportChartView/index.vue';
import {
  delReport,
  createReport,
  exportDataList,
  exportDataReport
} from '@/apis/pcf/report/report';
import { IReportResult } from '@/apis/pcf/report/model/reportModel';

import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import type { TableButtonItem } from '@/components/CTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import { StandardDetailMap } from '@/constants/enum';
import type { GetListVisibleModelResult } from '@/apis/pcf/pcfForm/model/pcfFormModel';
import ModelSelectDialog from '@/businessComponents/ModelSelectDialog/index.vue';
const { createConfirm, createMessage } = useMessage();
const { searchOptions, searchForm, tableOptions, tableFieldsSetting } = useReportList();
const { handleExportFile, handleDomsToImgs } = useExport();
import { ElLoading } from 'element-plus/lib/components';
import { renderResultUnit } from '@/utils';

const options = reactive<CPageTableProps>({
  title: '碳足迹报告',
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});

const dialogVisible = ref(false);
const imgLoadingInstance = ref();

const handleAdd = () => {
  dialogVisible.value = true;
};
const reportNo = ref('');
function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '下载报告',
      btnPermission: 'PCF_LCA_REPORT_DOWNLOAD',
      onClick: () => downReportBefore(row)
    },
    {
      text: '下载数据清单',
      btnPermission: 'PCF_LCA_REPORT_DOWNLOAD',
      onClick: () => downClick(row)
    },
    {
      text: '删除',
      btnPermission: 'PCF_LCA_REPORT_DELETE',
      onClick: () => deleteClick(row)
    }
  ];
}

const [registerPage, { refresh, setProps }] = useCPageTable(options);

const deleteClick = (row: IReportResult) => {
  createConfirm('确定删除该报告吗？', '删除后不可恢复！', {
    iconType: 'warning'
  }).then(async () => {
    await delReport(row.reportNo);
    createMessage.success(`${row.modelName}删除成功！`);
    handleRefresh();
  });
};

const downClick = (row: IReportResult) => {
  const params = {
    reportNo: row.reportNo
  };
  handleExportFile(exportDataList, params);
};
const downReportBefore = (row: IReportResult) => {
  // 下载前预处理
  if (row.reportNo) {
    reportNo.value = row.reportNo;
    imgLoadingInstance.value = ElLoading.service({
      fullscreen: true,
      lock: true,
      text: '文件生成中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  } else {
    createMessage.error('报告不存在！');
  }
};

const handleSelect = async (row: GetListVisibleModelResult) => {
  try {
    await createReport(row.modelNo);
    dialogVisible.value = false;
    createMessage.success(`创建报告成功！`);

    handleRefresh();
  } catch {
    console.log('error');
  }
};
useKeepAliveRefresh(refresh);
const handleRefresh = () => {
  refresh(true);
};

const finishHandle = () => {
  handleDomsToImgs(['#chart1', '#chart2'], 'URL')
    .then(async (res: any) => {
      imgLoadingInstance.value && imgLoadingInstance.value.close();
      const params = {
        reportNo: reportNo.value,
        exportDataUrl: [
          {
            name: 'REPORT_PRODUCT_LIFECYCLE',
            url: res && res.length ? res[0] : ''
          },
          {
            name: 'RAW_MATERIAL_OBTAIN_PROCESS',
            url: res && res.length > 0 ? res[1] : ''
          }
        ]
      };
      handleExportFile(exportDataReport, params);
    })
    .catch(() => {
      imgLoadingInstance.value && imgLoadingInstance.value.close();
      createMessage.error('报告生成失败，请重新点击下载');
    });
};
</script>

<style lang="scss" scoped>
.report-list {
  min-height: 80%;
}
</style>
